<template>
	<div class="cart-container">
		<van-nav-bar class="page-nav-bar" title="购物车" />
    <!-- 已登录 -->
		<template v-if="token">
			<van-empty v-if="!cartList.length" description="购物车暂无商品">
				<van-button
					round
					type="danger"
					to="/catalog"
					class="bottom-button"
					>快选挑选吧</van-button
				>
			</van-empty> 
			<div class="cartList" v-else>
        <van-swipe-cell  v-for="item in cartList" :key="item.id">
          <div class="item" >
           <van-checkbox v-model="item.checked" class="checkbox"></van-checkbox>
           <van-card
            class="item-cartd"
              :price="item.price"
              :desc="item.productAttr || '无规格' "
              :title="item.productName"
              :thumb="item.productPic"
            >
            <template #tags>
              <van-tag plain type="success">{{item.productBrand}}</van-tag>
            </template>
             <template #num>
              <van-stepper  @plus="changeNum(item,1)" @minus="changeNum(item,0)" :default-value="item.quantity" max="2" />
            </template>
          </van-card>
        </div>
        <template #right>
          <van-button square text="删除" @click="delCart(item)" type="danger" class="delete-button" />
        </template>
      </van-swipe-cell>
      </div> 
		</template>
    <!-- 未登录 -->
		<template v-else>
			<van-empty description="您还未登录">
				<van-button
					round
					type="danger"
					to="/login"
					class="bottom-button"
					>立即登录</van-button
				>
			</van-empty>
		</template>
    <!-- 底部栏 -->
    <van-submit-bar  v-if="token" :price="allPrice" button-text="提交订单" @submit="onSubmit">
      <van-checkbox v-model="isCheckAll">全选</van-checkbox>
    </van-submit-bar>
	</div>
</template>
<script>
import {   mapGetters } from 'vuex'
import {
  getCartList,
  delCart,
  updateCart,
} from '@/api/cart'
export default {
  name:'Cart',
	data() {
		return {
      cartList:[]
		}
	},
	created() {
		if (this.token) this.initData()
	},
	computed: {
		isCheckAll:{
      get(){
        return this.cartList.every(item => item.checked) && this.cartList.length
      },
      set(val){
        this.cartList.forEach(item=>{
          item.checked = val
        })
      }
    },
    allPrice(){
      return this.cartList.filter(item=>item.checked).reduce((sum,item)=> sum+= item.price * item.quantity,0)*100
    },
    ...mapGetters(['token'])
	},
	methods: {
    // 获取列表
    async initData(){
      const list = await getCartList()
      // 处理数据
      this.cartList = list.map(item=>{
        item.checked = false
        item.productAttr = JSON.parse(item.productAttr)
        if(item.productAttr.length){
          item.productAttr = item.productAttr.map(item=>{
            return item.key+':'+item.value
          }).join(',')
        }else{
          item.productAttr = ''
        }
        return item
      })
    },
    // 提交订单
    onSubmit(){
      const has = this.cartList.some(item=>item.checked)
      if(!has) return this.$toast.fail('请勾选商品')
      let cartIds =  this.cartList.filter(item=>item.checked).map(item=>item.id)
      this.$router.push('/checkout?cartIds='+cartIds.join(','))
      
    },
    // 修改当行的数量
    async  changeNum(val,type){
      const newNum =  type === 1 ? val.quantity+1 :  val.quantity-1 
      await updateCart({ id:val.id,quantity:newNum })
      val.quantity = newNum
    },
    // 删除购物车
    async delCart(val){
      await this.$dialog.confirm({title:'提示',message:'确定删除吗？'})
      await delCart({ids:val.id})
      this.$toast.success('删除成功')
      this.initData()
    }
	},
}
</script>
<style lang="less" scoped>
.cart-container {
	padding: 100px 0px;
	box-sizing: border-box;
	.page-nav-bar {
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
	}
  .van-card{
    background-color: #fff;
  }
  .delete-button {
    height: 100%;
  }
  .item{
    display: flex;
    margin-bottom: 4px;
    border-top: 1px solid #fafafa;
    border-bottom: 1px solid #fafafa;
    background-color: #fff;

    .checkbox{
      position: relative;
      z-index: 100;
      left: 20px;
    }
    .item-cartd{
      flex: 1;
    }
  }
  .van-submit-bar{
    bottom: 100px;
    border-bottom: 1px solid #fafafa;
  }
}
</style>
